<template>
  <div class="user">
    <!-- 头部 -->
    <a-form
      ref="formRef"
      style="padding-top: 20px"
      class="main-bg-color"
      :model="searchForm"
      :hideRequiredMark="true"
      :label-col="labelCol"
    >
      <a-row :gutter="20">
        <a-col :span="5" :lg="5" :xs="10">
          <a-form-item name="pushType" label="发送端口">
            <a-select ref="select" v-model:value="searchForm.pushType" @change="handleChange" placeholder="请选择">
              <a-select-option v-for="item in swiperTypes" :value="item.id" :key="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="5" :lg="5" :xs="12">
          <a-form-item name="sendStatus" label="发送端口">
            <a-select ref="select" v-model:value="searchForm.sendStatus" @change="handleChange" placeholder="请选择">
              <a-select-option v-for="item in sendStatus" :value="item.id" :key="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6" :lg="6" :xs="12">
          <a-form-item name="messageLikeName">
            <a-input v-model:value="searchForm.messageLikeName" placeholder="请根据消息编号，消息名称模糊查询"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="2" :offset="1">
          <a-button type="primary" @click="search" class="d-a-center">搜索</a-button>
        </a-col>
      </a-row>
    </a-form>

    <a-row justify="end" style="padding: 20px 20px">
      <a-col :span="2">
        <a-button type="primary" @click="sendBlack" v-has="{ a: $route, b: 2 }" class="d-a-center">黑名单</a-button>
      </a-col>
      <a-col :span="2" :offset="1">
        <a-button type="primary" @click="send" v-has="{ a: $route, b: 2 }" class="d-a-center">发布消息</a-button>
      </a-col>
    </a-row>
    <!-- 列表 -->
    <a-table
      :columns="columns"
      :data-source="list"
      bordered
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      :row-selection="rowSelection"
    >
      <template #pushType="{ record, index }">
        {{ ['', '护士端 ', '用户端'][record.pushType] }}
        <!-- <a-switch
          v-model:checked="record.status"
          :checkedValue="1"
          :unCheckedValue="0"
          @change="changeStatus(record.status, index)"
        /> -->
      </template>
      <template #sendStatus="{ record, index }">
        {{ ['待发送  ', '已发送'][record.sendStatus] }}
      </template>
      <template #operation="{ record }">
        <a-button type="link" @click="look(record.key, '编辑')" v-has="{ a: $route, b: 2 }">编辑</a-button>
        <a-button type="link" @click="look(record.key)" v-has="{ a: $route, b: 1 }">查看</a-button>
        <a-button type="link" danger @click="del(record.key, true)" v-has="{ a: $route, b: 2 }">删除</a-button>
      </template>
    </a-table>
    <a-divider></a-divider>
    <a-row>
      <!-- <a-col :span="2">
        <a-button type="danger" @click="deleteList">删除</a-button>
      </a-col> -->
    </a-row>
    <a-modal width="800px" :destroyOnClose="true" v-model:visible="blackvisible" title="黑名单" :footer="null" @cancle="closeBlack">
      <div class="wrap">
        <div class="top flex" style="margin-bottom: 30px">
          <a-input width="60" type="text" placeholder="请输入用户手机号" v-model:value="phone" />
          <a-button @click="addBlack" style="margin-left: 40px" class="d-a-center">添加</a-button>
        </div>
        <a-tag closable @close="hancleClose(i.blackPhone)" v-for="(i, index) in blackList" :key="index">{{ i.blackPhone }}</a-tag>
        <!-- <a-pagination
          v-model:current="current"
          :total="blackTotal"
          show-less-items
        /> -->
      </div>
    </a-modal>
    <!-- 创建push -->
    <a-modal width="800px" :destroyOnClose="true" v-model:visible="visible" :title="title" :footer="null" @cancle="cancle">
      <a-form ref="editRef" :model="editForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="发送端口" name="pushType">
          <a-radio-group :disabled="title == '查看'" v-model:value="editForm.pushType" name="pushType">
            <!-- <a-radio :value="0">所有用户</a-radio> -->
            <a-radio :value="1">护士端</a-radio>
            <a-radio :value="2">用户端</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="消息名称" name="messageName">
          <a-input placeholder="请输入消息名称,10个字符内" maxlength="10" v-model:value="editForm.messageName"></a-input>
        </a-form-item>
        <a-form-item label="消息标题" name="messageTitle">
          <a-input placeholder="请输入消息标题,20个字符内" maxlength="20" v-model:value="editForm.messageTitle"></a-input>
        </a-form-item>
        <a-form-item label="消息内容" name="messageContent">
          <a-input placeholder="请输入消息内容,40个字符内" maxlength="40" v-model:value="editForm.messageContent"></a-input>
        </a-form-item>
        <a-form-item name="downType" label="落地页面">
          <a-select ref="select" v-model:value="editForm.downType" @focus="focus" @change="handleChange" placeholder="请选择">
            <a-select-option :value="1">启动</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="接收条件" name="acceptType">
          <a-radio-group :disabled="title == '查看'" v-model:value="editForm.acceptType" @change="handleOptions" name="acceptType">
            <!-- <a-radio :value="0">所有用户</a-radio> -->
            <a-radio :value="1">全部用户</a-radio>
            <a-radio :value="2">目标城市</a-radio>
            <a-radio :value="3">上传用户</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item v-if="editForm.acceptType == 2">
          <a-select
            ref="select"
            mode="multiple"
            :disabled="title == '查看'"
            placeholder="请选择城市"
            :options="citys"
            v-model:value="editForm.cityName"
          >
            <!-- <a-select-option
              v-for="(item, index) in citys"
              :value="item.cityCode"
              :key="index"
              >{{ item.cityName }}</a-select-option
            > -->
          </a-select>
        </a-form-item>
        <a-form-item v-if="editForm.acceptType == 3" class="df">
          <div class="df">
            <a-button style="margin-right: 20px" class="d-a-center"
              ><a href="http://     41.27.119:7009/userWeb/unipushUpload/unipushTemplate.xlsx" target="_blank">参照模版</a></a-button
            >
            <a-upload
              v-if="title != '查看'"
              v-model:file-list="contentImg"
              name="file"
              :maxCount="1"
              :customRequest="handleChangeFile"
              :beforeUpload="beforeUpload"
            >
              <a-button class="d-a-center">
                <upload-outlined></upload-outlined>
                上传文件
              </a-button>
            </a-upload>
          </div>
        </a-form-item>
        <a-form-item label="发送时间" name="sendType">
          <a-radio-group :disabled="title == '查看'" v-model:value="editForm.sendType" name="sendTime" @change="handleChange">
            <!-- <a-radio :value="0">所有用户</a-radio> -->
            <a-radio :value="1">立即</a-radio>
            <a-radio :value="2">定时</a-radio>
          </a-radio-group>
          <a-date-picker show-time v-if="editForm.sendType == 2" valueFormat="YYYY-MM-DD HH:mm:ss" v-model:value="editForm.sendTime" />
        </a-form-item>
        <!-- <a-form-item name="sendTime" label=""> -->
        <!-- </a-form-item> -->
      </a-form>
      <a-row style="text-align: center">
        <a-col :span="4" :offset="8" v-if="title != '查看'">
          <a-button type="primary" @click="save" class="d-a-center">保存</a-button>
        </a-col>
        <a-col :span="4" :offset="title == '查看消息' ? 10 : 2">
          <a-button type="info" @click="cancle" class="d-a-center">关闭</a-button>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>
<script>
import moment from 'moment'
import { reactive, ref, watch, computed, defineComponent, createVNode, toRefs } from 'vue'
import { CheckOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import {
  pushList,
  addPushActivity,
  pushActivityWatch,
  deletePushActivity,
  queryPushBlackPhone,
  deletePushBlackPhone,
  addPushBlackPhone,
  uploadExcel,
  downExcel,
  queryCity
} from '@/api/setting/index'
import { useStore } from 'vuex'
import { useModal } from '@/hooks'

export default {
  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined
  },
  setup() {
    const store = useStore()
    console.log(store.state.userId, '用户ID是------------')
    const router = useRouter()
    const route = useRoute()
    const formRef = ref('')
    const form = reactive({})
    // 表单验证
    const rules1 = {}
    const data = reactive({
      blackvisible: false,
      phone: '',
      blackList: [],
      current: 1,
      blackTotal: 0,
      searchForm: {}, //发布者ID
      time: [],
      list: [],
      editForm: {},
      citys: [],
      contentImg: [],
      sendStatus: [
        { name: '待发送 ', id: 0 },
        { name: '已发送 ', id: 1 }
      ],
      swiperTypes: [
        { name: '护士端 ', id: 1 },
        { name: '用户端 ', id: 2 }
      ]
    })
    const editRef = ref('')
    const title = ref('编辑')

    const visible = ref(false)
    const rules = {
      pushType: [{ required: true, message: '请选择' }],
      messageContent: [{ required: true, message: '请输入' }],
      messageName: [{ required: true, message: '请输入' }],
      messageTitle: [{ required: true, message: '请输入' }],
      sendType: [{ required: true, message: '请选择' }],
      downType: [{ required: true, message: '请选择' }],
      acceptType: [{ required: true, message: '请选择' }]
      // content: [
      //   { required: true, message: "请输入短信内容!", trigger: "blur" },
      // ],
    }

    const loading = ref(true) //表格的加载

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    })
    // 查询
    const search = () => {
      console.log(data.searchForm, '表单内容')
      page.current = 1
      init()
    }

    const columns = [
      {
        title: '消息编号',
        dataIndex: 'id',
        className: 'table',
        align: 'center'
      },
      {
        title: '消息名称',
        dataIndex: 'messageName',
        className: 'table',
        align: 'center'
      },
      {
        title: '消息标题',
        dataIndex: 'messageTitle',
        className: 'table',
        align: 'center'
      },
      {
        title: '发送端口',
        dataIndex: 'pushType',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'pushType'
        }
      },
      {
        title: '创建时间',
        dataIndex: 'createdTime',
        className: 'table',
        align: 'center'
      },
      {
        title: '发送状态',
        dataIndex: 'sendStatus',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'sendStatus'
        }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        align: 'center',
        fixed: 'right',
        slots: {
          customRender: 'operation'
        }
      }
    ]

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, '当前分页')
      page.current = pagination.current
      page.pageSize = pagination.pageSize

      // 请求列表接口
      init()
    }

    // 全选反选
    const rowSelection = ref({
      checkStrictly: false,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
        delListId.value = selectedRowKeys
      },
      onSelect: (record, selected, selectedRows) => {
        // console.log(record, selected, selectedRows,'选择多项');
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        // console.log(selected, selectedRows, changeRows,'全选操作');
      }
    })
    const delListId = ref([]) //删除数组ID集合
    // 发送短信
    const send = () => {
      title.value = '新增'
      visible.value = true
      data.contentImg = []
      data.editForm = {}
    }
    const sendBlack = async () => {
      data.blackvisible = true
      let res = await queryPushBlackPhone()
      if (res.success) {
        data.blackList = res.object
      }
    }
    const hancleClose = phone => {
      deletePushBlackPhone({ phone }).then(r => {
        message.success('操作成功')
      })
    }
    const addBlack = () => {
      if (data.phone) {
        let reg = /^1[0-9]\d{9}$/
        if (!reg.test(data.phone)) {
          message.error('手机号格式错误')
          return
        }
      } else {
        message.error('请输入手机号')
        return
      }
      addPushBlackPhone({ phone: data.phone }).then(r => {
        if (r.success) {
          data.phone = ''
          message.success('添加成功')
          queryPushBlackPhone().then(res => {
            if (res.success) {
              data.blackList = res.object
            }
          })
        }
      })
    }
    const cancle = () => {
      visible.value = false
      data.editForm = {}
    }

    // 查看
    const look = (key, str = '查看') => {
      title.value = str
      initDetail(key)

      visible.value = true
    }
    const save = () => {
      console.log(data.editForm, 'editFormeditFormeditFormeditForm')
      editRef.value.validate().then(async () => {
        // if (!data.editForm.type) {
        //   message.error("请选择发送对象");
        //   return;
        // }
        // 上传文件
        if (data.editForm.acceptType == 3) {
          if (data.contentImg.length == 0) {
            message.error('请上传用户')
            return
          }
        }
        if (data.editForm.sendType == 2) {
          if (data.editForm.sendTime) {
            let now = moment().format('YYYY-MM-DD HH:mm:ss')
            console.log(now, data.editForm.sendTime, 111)
            if (!moment(data.editForm.sendTime).isAfter(now)) {
              message.error('选择日期需大于当前日期')
              return
            }
          } else {
            message.error('请选择日期')
            return
          }
        }
        if (data.editForm.acceptType == 2) {
          if (data.editForm.cityName.length < 1) {
            message.error('请选择目标城市')
            return
          }
          data.editForm.cityName = data.editForm.cityName.join(',')
        }
        let res = await addPushActivity(data.editForm)
        if (res.success) {
          visible.value = false
          message.success('已成功发送')
          page.current = 1
          init()
        }
      })
    }
    // 处理
    const del = (key, flag) => {
      let data = {}
      data.id = key
      const { closeModal } = useModal.confirm({
        title: '确定删除当前系统通知吗?',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          let res = await deletePushActivity(data)
          if (res.success) {
            message.success('删除成功')
            init()
            closeModal()
          }
        }
      })
    }
    const handleOptions = e => {
      if (e.target.value == 2) {
        getCitys()
      }
    }
    const handleChange = e => {
      //  if(e.target.value==2){
      //  }
    }
    const handledownExcel = async () => {
      // let r = await downExcel();
    }
    const beforeUpload = () => {
      return new Promise((resolve, reject) => {
        if (data.contentImg.length > 0) {
          message.error('请删除已存在的文件再上传')
          reject(false)
        }
        resolve(true)
      })
    }

    const handleChangeFile = file => {
      console.log(file)
      uploadImage(file, 'contentImg')
    }
    // 公共的上传图片
    const uploadImage = async (file, e) => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadExcel(formData, 'ali')
      // // url存入列表中,为什么是两个fileList
      data[e] = data[e].filter(el => el.status == 'done')
      if (res.success) {
        data.editForm['excelPath'] = res.object
        data[e].push({
          uid: file.file.uid,
          url: res.object,
          status: 'done',
          name: file.file.name
        })
      }
      console.log(data[e], 'data[e]是--')
    }
    const getCitys = async () => {
      let res = await queryCity()
      data.citys = res.object.map(m => {
        return {
          value: m.cityName
        }
      })
    }
    const deleteList = () => {
      console.log(delListId.value)
      if (delListId.value.length == 0) {
        message.warning('请选择你要删除的系统通知')
        return
      }
      del(delListId.value)
    }
    init()
    async function init() {
      loading.value = true
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        ...data.searchForm
      }
      let res = await pushList({ ...obj })
      if (res.success) {
        res.object.list.map(el => (el.key = el.id))
        data.list = res.object.list
        page.total = res.object.total
        loading.value = false
      }
    }
    async function initDetail(id) {
      let res = await pushActivityWatch({ id })
      if (res.success) {
        data.editForm = res.object
      }
    }
    const closeBlack = () => {
      data.blackvisible = false
      data.phone = ''
    }
    return {
      ...toRefs(data),
      formRef,
      form,
      rules,
      rules1,
      columns,
      loading,
      pagination,
      handleTableChange,
      search,
      del,
      look,
      rowSelection,
      labelCol: { style: { fontWeight: 'bolder', width: '100px' } },
      send,
      visible,
      editRef,
      title,
      cancle,
      save,
      deleteList,
      handleChange,
      handleChangeFile,
      beforeUpload,
      uploadImage,
      handleOptions,
      getCitys,
      handledownExcel,
      sendBlack,
      addBlack,
      hancleClose,
      closeBlack
    }
  }
}
</script>
<style scoped lang="less"></style>
